#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''连接MongoDB'''

import os
from pymongo import MongoClient
from time import strftime, localtime


class MongoDB(object):
    orderTable = None

    def __init__(self):
        self.client, self.orderTable = self.get_clientAndTable()

    def get_clientAndTable(self):
        client = MongoClient("mongodb://{0}:{1}@{2}/admin".format(
            "root", "eisoo.com", "10.2.184.160:27017,10.2.184.161:27017,10.2.184.162:27017"))
        db = client.userOrder
        orderTable = db.userOrderTable
        return client, orderTable

    def close_client(self):
        self.client.close()

    def get_allData(self):
        return self.orderTable.find()

    def get_dataByName(self, name):
        return self.orderTable.find({"name": name})

    def get_dataByID(self, id):
        return self.orderTable.find({"_id": id})

    def insert_Data(self, name, pwd, isOrder=0, position="sh", orderType="Launch", orderTime=strftime("%Y-%m-%d %H:%M:%S", localtime()), weChartID="", email="", isUse=0, order_status=0):
        values = [0, 1]
        if (isOrder not in values) and (isUse not in values) and (self.orderTable not in values):
            return False
        self.orderTable.insert_one({"name": name, "pwd": pwd, "isOrder": isOrder, "orderTime": orderTime, "position": position, "orderType": orderType,
                                    "weChartID": weChartID, "email": email, "isUse": isUse, "order_status": order_status})
        return True

    def update_orderDataByName(self,  name, isOrder=0, orderTime=strftime("%Y-%m-%d %H:%M:%S", localtime()), position="sh", orderType="Launch"):
        self.orderTable.update_one(
            {"name": name}, {"$set": {"isOrder": isOrder, "orderTime": orderTime, "position": position, "orderType": orderType}})

    def update_manageDataByName(self,  name, isUse=0, order_status=0):
        self.orderTable.update_one(
            {"name": name}, {"$set": {"isUse": isUse, "order_status": order_status}})

    def update_userDataByName(self,  name, weChartID="weChartID"):
        self.orderTable.update_one(
            {"name": name}, {"$set": {"weChartID": weChartID}})


if __name__ == "__main__":
    db = MongoDB()
    db.insert_Data("Jack", "123456", weChartID="", email='Jack.zeng@aishu.cn')
    db.insert_Data("jack", "123456", weChartID="", email='Jack.zeng@aishu.cn')
    db.insert_Data("Leo", "123456", weChartID="", email='Leo.li@aishu.cn')
    db.insert_Data("leo", "123456", weChartID="", email='Leo.li@aishu.cn')
    for i in db.get_allData():
        print(i)
